package com.example.demo.controller;

import com.example.demo.entity.SysUser;
import com.example.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//调用service层
@Controller
//自动识别跳转路径
@RequestMapping("/user")
public class SysUserController {
    SysUserService service;
    @Autowired
    public SysUserController(SysUserService service){
        this.service=service;
    }
    @RequestMapping("/list")//和HTML文件对标
    public String list(Model model){
        //通过model传值到页面
        List<SysUser> list=service.getAll();
        model.addAttribute("list",list);//model打包成list属性完成List对象的值传递
        return "/user/list";
    }
    @RequestMapping(value = "/insert")//跳转到edit页面
    public String insert(Model model){
        model.addAttribute("user",new SysUser());//同步传递到edit
        return "/user/edit";
    }


    @RequestMapping(value = "/edit/{id}")
    public String entity(@PathVariable("id") Long id,Model model){
        SysUser entity=service.getById(id);
        model.addAttribute("user",entity);
        return "/user/edit";
    }

    //用来存储表单提交数据
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(@ModelAttribute("user") SysUser entity){//执行后提交到后端
//        if(entity.getId()!=null){
//            service.update(entity);
//        }else {
//            service.insert(entity);
//        }
        boolean result=entity.getId()!=null?service.update(entity):service.insert(entity);
        //对result进行判断,当非0时跳转到list,否则
//        return result>0?"/user/list":"数据错误";
        return "redirect:/user/list";
    }


    //详情
    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id")Long id,Model model){

        SysUser entity=service.getById(id);
        model.addAttribute("user",entity);
        return "/user/detail";
    }


    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id")Long id){
        boolean entity=service.delete(id);
        return "redirect:/user/list";
    }
}
